// 所有文件下载请求
import request from '@/utils/request'
import { Message } from 'element-ui'
class DOWNLOAD {
    constructor() {
        // ...
    }
    exportExcel(url, params) {
        request({
            method: 'get',
            url: url,
            params: params,
            responseType: 'blob'
        }).then(response => {
            console.log(response)
            console.log(params)
            this.download(response.data,`${params.projectid}.xls`);
        }).catch((error) => {
            let reader = new FileReader();
            reader.onload = function (event) {
                //let msg = JSON.parse(reader.result).state.msg;
                let resultObj = reader.result;
                let msg = resultObj;
                if(JSON.parse(resultObj).state)
                {
                  msg = JSON.parse(resultObj).state.msg;
                }
                Message({
                    message: msg,
                    type: 'error'
                })
            };
            reader.readAsText(error.data)
        })
    }
    // 下载文件
    download(data, fileName) {
        if (!data) {
            return 'false';
        }
        this.createToDownload(window.URL.createObjectURL(new Blob([data])), fileName)
    }
    createToDownload(url, fileName) {
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        let transformFileName = decodeURIComponent(fileName)
        link.setAttribute('download', transformFileName);
        document.body.appendChild(link);
        link.click();
    }
}

export default DOWNLOAD;
